package com.zy.list.list

import android.content.Intent
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.FragmentManager
import com.zy.list.DIYMainActivity
import com.zy.list.ListConstant.ARG_PARENT_ID
import com.zy.list.R

import com.zy.storage.doc.DocInfo

class MyDocItemRecyclerViewAdapter(
    private val values: List<DocInfo>,
    private val fragmentManager: FragmentManager
) : RecyclerView.Adapter<MyDocItemRecyclerViewAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        return ViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.fragment_doc_list_item, parent, false)
        )

    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(values[position])
    }

    override fun getItemCount(): Int = values.size

    inner class ViewHolder(view: View) :
        RecyclerView.ViewHolder(view) {
        private val itemIcon: ImageView = view.findViewById(R.id.item_icon)
        private val itemMore: ImageView = view.findViewById(R.id.item_more)
        private val itemContent: TextView = view.findViewById(R.id.item_content)
        private val itemDes: TextView = view.findViewById(R.id.item_des)
        private var docInfo: DocInfo? = null

        init {
            view.setOnClickListener {
                docInfo?.let { info ->
                    if (info.fileType == 0) { //打开子文件夹
                        it.context.startActivity(
                            Intent(
                                it.context,
                                DIYMainActivity::class.java
                            ).apply {
                                putExtra(ARG_PARENT_ID, info.fileId)
                            })
                    } else {
                        //打开选择SheetFragment
                        //是编辑还是展示
                        OpenFileSelectFragment.show(fragmentManager, info.fileId)
                    }
                }
            }

            itemMore.setOnClickListener {
                docInfo?.let { info ->
                    FileOpFragment.show(fragmentManager, info.fileId)
                }
            }
        }

        fun bind(docInfo: DocInfo) {
            this.docInfo = docInfo
            itemContent.text = docInfo.title
            itemDes.text = docInfo.des
            if (docInfo.fileType == 0) {
                itemIcon.setBackgroundResource(R.drawable.folder_48)
            } else {
                itemIcon.setBackgroundResource(R.drawable.file_48)
            }
        }
    }

}